package com.zd.controller;

import com.zd.domain.PostLike;
import com.zd.domain.Result;
import com.zd.service.postlike.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/postlike")
public class PostLikeController {

    @Autowired
    private PostLikeService postLikeService;

    /**
     * 查询点赞
     * @param postId
     * @param userId
     * @return
     */
    @GetMapping("/findPostLike")
    public Result<PostLike> findPostLike(@RequestParam("postId") Integer postId,
                                         @RequestParam("userId") Integer userId){

        Result<PostLike> result = new Result<>();

        if ((postId != 0) && (userId != 0)){
            PostLike postLike = postLikeService.findPostLikeId(postId, userId);

            if (postLike != null){
                result.setCode(200);
                result.setMsg("查询成功！");
                result.setData(postLike);
            }else {
                result.setCode(400);
                result.setMsg("查询失败！");
            }
        }

        return result;

    }

    /**
     * 添加点赞
     * @return
     */
    @PostMapping("savePostLike")
    public Result savePostLike(@RequestBody PostLike postLike){

        Result result = new Result();

        if (postLike != null){
            //查询是否有这个人的点赞
            PostLike postLike1 = postLikeService.findPostLikeId(postLike.getPostId(), postLike.getUserId());

            if (postLike1 != null){
                result.setCode(201);
                result.setMsg("已点赞");
            }else {
                int i = postLikeService.savePostLike(postLike);

                if (i == 1){
                    result.setCode(200);
                    result.setMsg("点赞成功！");
                }else {
                    result.setCode(400);
                    result.setMsg("点赞失败！");
                }
            }
        }

        return result;

    }


    @DeleteMapping("/delPostLike")
    public Result delPostLike(@RequestParam("postLikeId") Integer postLikeId){

        Result result = new Result();

        if (postLikeId != 0){
            int i = postLikeService.delPostLike(postLikeId);

            if (i == 1){
                result.setCode(200);
                result.setMsg("删除成功！");
            }else {
                result.setCode(400);
                result.setMsg("删除失败！");
            }

        }

        return result;

    }




}
